Completed
Push — master ( eb99f6...7b33db )
by Bui Quang
10s
created

gfimage.js ➔ GFImage   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 156

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
c 3
b 0
f 0
nc 1
nop 0
dl 0
loc 156
rs 8.2857

9 Functions

Rating   Name   Duplication   Size   Complexity  
A gfimage.js ➔ ... ➔ this.init 0 4 1
A gfimage.js ➔ ... ➔ this._onClickGButton 0 10 1
A gfimage.js ➔ ... ➔ this._progressBarInit 0 6 1
A gfimage.js ➔ ... ➔ this._toggleButton 0 14 1
A gfimage.js ➔ ... ➔ this._ajaxUpdateFImage 0 19 1
B gfimage.js ➔ ... ➔ this._updateLogAfterAjax 0 15 5
A gfimage.js ➔ ... ➔ this._warning 0 4 1
A gfimage.js ➔ ... ➔ this._updateProgressBar 0 8 1
A gfimage.js ➔ ... ➔ this._continueAjax 0 18 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
import progressbar from 'progressbar.js';
2
3
var GFImage = function() {
4
5
	var $ = jQuery;
6
7
	var gFImage = this;
8
9
	var element = $('#generate_fimage_wrapper');
10
11
	var postNoFImageIds = element.data('post_no_fimage_ids');
12
13
	var totalPostNoFImage = postNoFImageIds.length;
14
15
	var securityToken = element.data('nonce');
16
17
	var informationWrapper = $('.generate-fimage-information');
18
19
	var progressBarID = '#generate_fimage_progressbar';
20
21
	var progressBar;
22
23
	var generateButton = $('#generate_fimage_button');
24
25
	var saveButton = $('#save_form_button');
26
27
	this.init = function() {
28
		gFImage._progressBarInit();
29
		gFImage._onClickGButton();
30
	}	
31
32
	/**
33
	 * Initialize progress bar.
34
	 */
35
	this._progressBarInit = function() {
36
		var ProgressBar = require('progressbar.js');
37
		progressBar = new ProgressBar.Line(progressBarID, {
38
	        easing: 'easeInOut'
39
	    });
40
	}
41
42
	/** 
43
	 * Actions after generate button is clicked.
44
	 */
45
	this._onClickGButton = function() {
46
		generateButton.click(function(event){
47
			event.preventDefault();
48
			var warningResult = gFImage._warning();
49
			if(warningResult) {
50
				gFImage._toggleButton([generateButton, saveButton], 'disable');
51
				gFImage._ajaxUpdateFImage(postNoFImageIds[0]);
52
			}
53
		});
54
	}
55
56
	/**
57
	 * Enable, disable a list of buttons.
58
	 */
59
	this._toggleButton = function(arrayElement, status) {
60
		arrayElement.forEach(function(el){
61
			switch(status) {
62
				case 'disable':
63
					el.prop('disabled', true);
64
					break;
65
				case 'enable':
66
					el.prop('disabled', false);
67
					break;
68
				default:
69
					el.prop('disabled', false);
70
			}
71
		});
72
	}
73
74
	/**
75
	 * Regenerate feature image for a post.
76
	 */
77
	this._ajaxUpdateFImage = function(postId) {
78
		$.ajax({
79
            url: '/wp-admin/admin-ajax.php?action=wpdfi_generate_feature_image',
80
            method: 'POST',
81
            data: {
82
                post_id: postId,
83
                security: securityToken
84
            },
85
            success: function(res) {
86
87
            	var response = JSON.parse(res);
88
            	gFImage._updateLogAfterAjax(response);
89
            	var arrayIndex = postNoFImageIds.indexOf(postId);
90
            	gFImage._updateProgressBar(arrayIndex);
91
            	gFImage._continueAjax(arrayIndex);
92
93
            }
94
        })
95
	}
96
97
	/**
98
	 * Update the progress bar. Progress bar will be 100% if all the posts are regenerated feature image.
99
	 */
100
	this._updateProgressBar = function(arrayIndex) {
101
		/* Javascript array index start at 0, so we need to plus 1 to get the correct value for divide purpose. */
102
		var realIndex = arrayIndex + 1;
103
		var currentPercent = realIndex/totalPostNoFImage;
104
		var currentPercentText = (currentPercent*100).toFixed(2) + '%';
105
		progressBar.set(currentPercent);
106
		progressBar.setText(currentPercentText);
107
	}
108
109
	/**
110
	 * Check if there is a post which is not regenerated feature image yet.
111
	 */
112
	this._continueAjax = function(arrayIndex) {
113
		/* Javascript array index start at 0, so we need to minus 1 from total posts to get the last index. */
114
		var lastIndex = totalPostNoFImage - 1;
115
		var isLastIndex = (arrayIndex == lastIndex);
116
		/* If the current index is not the last index, continue run Ajax request on the next index. */
117
		if(!isLastIndex) {
118
			gFImage._ajaxUpdateFImage(postNoFImageIds[arrayIndex + 1]);
119
		/* If the current index is the last index, enable save button. */
120
		} else {
121
122
			gFImage._updateLogAfterAjax({
123
				status: 'complete',
124
				text: 'Complete!'
125
			});
126
			gFImage._toggleButton([saveButton], 'enable');
127
128
		}
129
	}
130
131
	/**
132
	 * Update log message after the generate button is clicked.
133
	 */
134
	this._updateLogAfterAjax = function(response) {
135
		switch(response.status) {
136
    		case true:
137
    			informationWrapper.append('<p>' + response.namePT + ' with ID ' + response.postId +' is updated feature image successfully</p>');
138
    			break;
139
    		case false:
140
    			informationWrapper.append('<p>' + response.namePT + ' with ID ' + response.postId +' because conditions are not match.</p>');
141
    			break;
142
    		case 'complete':
143
    			informationWrapper.append('<p>' + response.text + '</p>');
144
    			break;
145
    		default:
146
    			informationWrapper.append('<p>' + response.namePT + ' with ID ' + response.postId +' has something wrong!</p>');
147
    	}
148
	}
149
150
	/**
151
	 * Display alert box whenever the generate button is clicked.
152
	 */
153
	this._warning = function() {
154
		var warningText = 'Are you sure you want to generate all feature image with the values in the "DFIs" tab? Make sure to backup your database before click "OK".';
155
		return confirm(warningText);
156
	}
157
158
}
159
160
export default GFImage;